package com.byd.sealmanage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.byd.sealmanage.config.CommonResultOutput;
import com.byd.sealmanage.dao.mybatis.*;
import com.byd.sealmanage.modal.bo.ChangeWorkParamVO;
import com.byd.sealmanage.modal.po.*;
import com.byd.sealmanage.service.WorkManageService;
import com.byd.sealmanage.util.JsonUtil;
import com.byd.sealmanage.util.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class WorkManageServiceImpl implements WorkManageService {

    @Autowired
    private TbSealChangeMapper tbSealChangeMapper;

    @Autowired
    private TbRoleMapper tbRoleMapper;

    @Autowired
    private TbKeepPeopleMapper tbKeepPeopleMapper;

    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    private TbDivisionSealMapper tbDivisionSealMapper;

    /**
     * 获取印章转交信息
     * @return
     */
    @Override
    public JSONObject getChangeDataService(ChangeWorkParamVO changeWorkParamVO,TbUser loginUser) {
        CommonResultOutput commonResultOutput;
        JSONObject jsonObject = new JSONObject();
        try{
            int begin = (changeWorkParamVO.getPage() - 1)* changeWorkParamVO.getPageSize();
            changeWorkParamVO.setBegin(begin);
            changeWorkParamVO.setLoginUser(loginUser.getJobnumber());
            //工厂管理员——本工厂转交记录，地区管理员——本地区转交记录，事业部管理员——所有转交记录
            int totalCount = tbSealChangeMapper.selectChangeCount(changeWorkParamVO);
            jsonObject.put("total",totalCount);
            if(totalCount > 0){
                List<ChangeWorkParamVO> sealChangeData = tbSealChangeMapper.selectChangeData(changeWorkParamVO);
                for(ChangeWorkParamVO item : sealChangeData){
                    String[] sealPictures = item.getSealPattern().split("sealPicture");
                    item.setSealPattern("localFile" + sealPictures[1]);
                }
                jsonObject.put("rows",sealChangeData);
                commonResultOutput = new CommonResultOutput(200,"查询成功",jsonObject);
            }else{
                commonResultOutput = new CommonResultOutput(999,"查询结果为空",jsonObject);
            }
        }catch(Exception e){
            log.info("获取印章转交信息接口出现异常");
            log.info(e.toString());
            commonResultOutput = new CommonResultOutput(999,"执行出现异常",jsonObject);
        }
        return JsonUtil.toJSONObject(commonResultOutput);
    }

    /**
     * 获取印章转交记录
     * @param changeWorkParamVO
     * @param loginUser
     * @return
     */
    @Override
    public JSONObject getChangeRecordService(ChangeWorkParamVO changeWorkParamVO, TbUser loginUser) {
        CommonResultOutput commonResultOutput;
        JSONObject jsonObject = new JSONObject();
        try{
            int begin = (changeWorkParamVO.getPage() - 1)* changeWorkParamVO.getPageSize();
            changeWorkParamVO.setBegin(begin);
            TbRole userOneRole = tbRoleMapper.getUserOneRole(loginUser.getJobnumber());
            if("4".equals(userOneRole.getRoleId())){
                //普通用户
                changeWorkParamVO.setLoginUser(loginUser.getJobnumber());
            }else if("3".equals(userOneRole.getRoleId())){
                //工厂管理员
                changeWorkParamVO.setFactory(loginUser.getFactory());
            }else if("2".equals(userOneRole.getRoleId())){
                //地区管理员
                changeWorkParamVO.setPlace(loginUser.getWorkPlace());
            }
            //工厂管理员——本工厂转交记录，地区管理员——本地区转交记录，事业部管理员——所有转交记录
            int totalCount = tbSealChangeMapper.selectChangeRecordCount(changeWorkParamVO);
            jsonObject.put("total",totalCount);
            if(totalCount > 0){
                List<ChangeWorkParamVO> sealChangeData = tbSealChangeMapper.selectChangeRecordData(changeWorkParamVO);
                for(ChangeWorkParamVO item : sealChangeData){
                    String[] sealPictures = item.getSealPattern().split("sealPicture");
                    item.setSealPattern("localFile" + sealPictures[1]);
                }
                jsonObject.put("rows",sealChangeData);
                commonResultOutput = new CommonResultOutput(200,"查询成功",jsonObject);
            }else{
                commonResultOutput = new CommonResultOutput(999,"查询结果为空",jsonObject);
            }
        }catch(Exception e){
            log.info("获取印章转交信息接口出现异常");
            log.info(e.toString());
            commonResultOutput = new CommonResultOutput(999,"执行出现异常",jsonObject);
        }
        return JsonUtil.toJSONObject(commonResultOutput);
    }

    /**
     * 事业部印章转交时接收印章
     * @param changeId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject receiveDivisionSealService(String changeId) {
        CommonResultOutput commonResultOutput;
        Date date = new Date();
        try{
            TbSealChange tbSealChange = tbSealChangeMapper.selectByPrimaryKey(changeId);
            //修改转交印章的状态
            TbKeepPeople tbKeepPeople = new TbKeepPeople();
            tbKeepPeople.setState("3");
            Example example = new Example(TbKeepPeople.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("workId",tbSealChange.getKeepWorkId());
            tbKeepPeopleMapper.updateByExampleSelective(tbKeepPeople,example);
            //修改印章转交记录的状态
            TbSealChange updateSealChange = new TbSealChange();
            updateSealChange.setChangeId(tbSealChange.getChangeId());
            updateSealChange.setReceiveDate(date);
            updateSealChange.setState("10");
            tbSealChangeMapper.updateByPrimaryKeySelective(updateSealChange);
            commonResultOutput = new CommonResultOutput("0000","接收成功");
        }catch(Exception e){
            log.info("事业部印章接收接口出现异常");
            log.info(e.toString());
            commonResultOutput = new CommonResultOutput("0000","接收成功");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return JsonUtil.toJSONObject(commonResultOutput);
    }

    /**
     * 退回印章
     * @param changeId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject refuseDivisionSealService(String changeId) {
        CommonResultOutput commonResultOutput;
        Date date = new Date();
        try{
            //根据不同的转交类型，执行相应的反操作
            TbSealChange tbSealChange = tbSealChangeMapper.selectByPrimaryKey(changeId);
            //转交的印章（底版印章）
            TbDivisionSeal tbDivisionSeal = tbDivisionSealMapper.selectByPrimaryKey(tbSealChange.getSealId());
            //原监印人信息
            TbKeepPeople oldKeepPeople = tbKeepPeopleMapper.selectByPrimaryKey(tbSealChange.getOldKeepId());
            //新监印人信息
            Example example = new Example(TbKeepPeople.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("workId",tbSealChange.getKeepWorkId());
            TbKeepPeople tbNewKeepPeople = tbKeepPeopleMapper.selectOneByExample(example);
            if("1".equals(tbSealChange.getState())){
                //某个印章全部跨部门转交
                //修改印章信息
                TbUser userByJobNumber = tbUserMapper.getUserByJobNumber(tbSealChange.getOldKeepNumber(), null);
                TbDivisionSeal updateSealInfo = new TbDivisionSeal();
                updateSealInfo.setSealId(tbSealChange.getSealId());
                updateSealInfo.setPlace(userByJobNumber.getWorkPlace());
                updateSealInfo.setFactory(userByJobNumber.getFactory());
                tbDivisionSealMapper.updateByPrimaryKeySelective(updateSealInfo);
                //修改监印人信息
                TbKeepPeople updateKeepPeople = new TbKeepPeople();
                updateKeepPeople.setTfId(tbSealChange.getOldKeepId());
                updateKeepPeople.setKeepNumber(userByJobNumber.getJobnumber());
                updateKeepPeople.setKeepName(userByJobNumber.getUsername());
                updateKeepPeople.setKeepFactory(userByJobNumber.getFactory());
                updateKeepPeople.setKeepDepartment(userByJobNumber.getDepartment());
                updateKeepPeople.setKeepOffice(userByJobNumber.getOffice());
                updateKeepPeople.setUpdateTime(date);
                updateKeepPeople.setState("3");
                tbKeepPeopleMapper.updateByPrimaryKeySelective(updateKeepPeople);
            }else if("2".equals(tbSealChange.getState())){
                TbUser userByJobNumber = tbUserMapper.getUserByJobNumber(tbSealChange.getOldKeepNumber(), null);
                //该印章只转交部分给某个部门
                //修改原部门印章数量
                TbDivisionSeal oldSeal = new TbDivisionSeal();
                oldSeal.setSealId(tbSealChange.getSealId());
                Integer leftCount = tbDivisionSeal.getSealCount() + tbNewKeepPeople.getKeepCount();
                oldSeal.setSealCount(leftCount);
                tbDivisionSealMapper.updateByPrimaryKeySelective(oldSeal);
                //更新监印人信息
                TbKeepPeople updateKeepPeople = new TbKeepPeople();
                updateKeepPeople.setTfId(tbNewKeepPeople.getTfId());
                updateKeepPeople.setSealId(tbSealChange.getSealId());
                updateKeepPeople.setKeepNumber(userByJobNumber.getJobnumber());
                updateKeepPeople.setKeepName(userByJobNumber.getUsername());
                updateKeepPeople.setKeepFactory(userByJobNumber.getFactory());
                updateKeepPeople.setKeepDepartment(userByJobNumber.getDepartment());
                updateKeepPeople.setKeepOffice(userByJobNumber.getOffice());
                updateKeepPeople.setUpdateTime(date);
                updateKeepPeople.setState("3");
                tbKeepPeopleMapper.updateByPrimaryKeySelective(updateKeepPeople);
                //删除新加的印章
                tbDivisionSealMapper.deleteByPrimaryKey(tbNewKeepPeople.getSealId());
            }else if("3".equals(tbSealChange.getState())){
                //增加原部门印章数量
                TbDivisionSeal oldSeal = new TbDivisionSeal();
                oldSeal.setSealId(tbSealChange.getSealId());
                Integer leftCount = tbDivisionSeal.getSealCount() + tbNewKeepPeople.getKeepCount();
                oldSeal.setSealCount(leftCount);
                tbDivisionSealMapper.updateByPrimaryKeySelective(oldSeal);
                //增加原监印人的印章数量
                TbKeepPeople oldKeeper = new TbKeepPeople();
                oldKeeper.setTfId(tbSealChange.getOldKeepId());
                oldKeeper.setKeepCount(oldKeepPeople.getKeepCount() + tbNewKeepPeople.getKeepCount());
                tbKeepPeopleMapper.updateByPrimaryKeySelective(oldKeeper);
                //删除新的印章信息
                tbDivisionSealMapper.deleteByPrimaryKey(tbNewKeepPeople.getSealId());
                //删除新加的监印人
                tbKeepPeopleMapper.deleteByPrimaryKey(tbNewKeepPeople.getTfId());
            }else if("4".equals(tbSealChange.getState())){
                TbUser userByJobNumber = tbUserMapper.getUserByJobNumber(tbSealChange.getOldKeepNumber(), null);
                //非跨部门转交某人全部印章
                TbKeepPeople updateKeepPeople = new TbKeepPeople();
                updateKeepPeople.setTfId(tbSealChange.getOldKeepId());
                updateKeepPeople.setKeepNumber(userByJobNumber.getJobnumber());
                updateKeepPeople.setKeepName(userByJobNumber.getUsername());
                updateKeepPeople.setKeepFactory(userByJobNumber.getFactory());
                updateKeepPeople.setKeepDepartment(userByJobNumber.getDepartment());
                updateKeepPeople.setKeepOffice(userByJobNumber.getOffice());
                updateKeepPeople.setUpdateTime(date);
                updateKeepPeople.setState("3");
                tbKeepPeopleMapper.updateByPrimaryKeySelective(updateKeepPeople);
            }else{
                //非跨部门转交某人部分印章
                //增加原监印人的印章数量
                TbKeepPeople updateKeepPeople = new TbKeepPeople();
                updateKeepPeople.setTfId(tbSealChange.getOldKeepId());
                Integer leftCount = oldKeepPeople.getKeepCount() + tbNewKeepPeople.getKeepCount();
                updateKeepPeople.setKeepCount(leftCount);
                updateKeepPeople.setUpdateTime(date);
                tbKeepPeopleMapper.updateByPrimaryKeySelective(updateKeepPeople);
                //删除监印人信息
                tbKeepPeopleMapper.deleteByPrimaryKey(tbNewKeepPeople.getTfId());
            }
            //修改印章转交记录的状态
            TbSealChange updateSealChange = new TbSealChange();
            updateSealChange.setChangeId(tbSealChange.getChangeId());
            updateSealChange.setReceiveDate(date);
            updateSealChange.setState("15");
            tbSealChangeMapper.updateByPrimaryKeySelective(updateSealChange);
            commonResultOutput = new CommonResultOutput("0000","退回成功");
        }catch (Exception e){
            log.info("退回印章接口出现异常");
            log.info(e.toString());
            commonResultOutput = new CommonResultOutput("0000","执行出现异常");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return JsonUtil.toJSONObject(commonResultOutput);
    }
}
